﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
using System.Linq;
using System.Windows.Forms;
using CefSharp;
using CefSharp.WinForms;
using Dapper.Contrib.Extensions;
using Newtonsoft.Json.Linq;
using pinduoduo.Model;
using pinduoduo.Util;
using RestSharp;
using Tk.Soc.Share.Common.Helpers;

namespace pinduoduo
{
    public partial class AccountControl : UserControl
    {

        private string goodId;
        private ChromiumWebBrowser chromeBrowser;
        private RequestContext context;

        public AccountControl()
        {
            InitializeComponent();
        }

        private void AccountControl_Load(object sender, EventArgs e)
        {

        }

        //public PddSkuFrom(string goodId)
        //{
        //    this.goodId = goodId;
        //    InitializeComponent();
        //    this.goods_id.Text = this.goodId;
        //}

        //初始化浏览器并启动
        public void InitializeChromium()
        {

            context = new RequestContext(new RequestContextSettings()
            {
                CachePath = AppDomain.CurrentDomain.BaseDirectory + "caches\\global2\\",
                PersistSessionCookies = true,
                PersistUserPreferences = true
            });

            chromeBrowser = new ChromiumWebBrowser("http://yangkeduo.com/", context);

            chromeBrowser.KeyboardHandler = new CEFKeyBoardHander();
            //chromeBrowser.FrameLoadEnd += Browser_FrameLoadEnd;

            this.panel1.Controls.Add(chromeBrowser);

            chromeBrowser.Dock = DockStyle.Fill;
        }

        public static bool IsPropertyExist(dynamic data, string propertyname)
        {
            if (data is ExpandoObject)
                return ((IDictionary<string, object>)data).ContainsKey(propertyname);
            return data.GetType().GetProperty(propertyname) != null;
        }

        private void button4_Click(object sender, EventArgs e)
        {

            string script = @"(function() { return  window.rawData.store.initDataObj.goods;})()";
            PddGood pddGood = new PddGood();
            chromeBrowser.EvaluateScriptAsync(script).ContinueWith(x =>
            {
                var response = x.Result;

                if (response.Success && response.Result != null)
                {
                    dynamic obj = response.Result;
                    dynamic skuObj = obj.skus;
                    if (IsPropertyExist(obj, "activity") && IsPropertyExist(obj.activity, "activityID"))
                    {
                        pddGood.atvid = obj.activity.activityID + "";
                    }

                    pddGood.gID2 = obj.groupTypes[0].groupID + "";
                    pddGood.gID1 = obj.groupTypes[1].groupID + "";
                    pddGood.good_id = obj.goodsID + "";
                    string skuJson = JsonHelper.SerializeObject(skuObj);

                    pddGood.sku = skuJson;
                    pddGood.type = 0;
                    PddGood pdd = DataBaseHelper.SqLiteDBCon.Get<PddGood>(pddGood.good_id);
                    if (pdd == null)
                    {
                        long reslut = DataBaseHelper.SqLiteDBCon.Insert<PddGood>(pddGood);
                    }
                    else
                    {
                        DataBaseHelper.SqLiteDBCon.Update<PddGood>(pddGood);
                    }
                    MessageBox.Show("获取数据成功");

                }
                else
                {
                    MessageBox.Show("获取数据失败");
                }
            });

        }

        private async void button1_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(this.goodId))
            {
                string goodId = this.goodId.Replace("\n", "").Replace(" ", "").Replace("\t", "").Replace("\r", "");


                await context.GetCookieManager(null).FlushStoreAsync();

                List<CefSharp.Cookie> cookies2 = await context.GetCookieManager(null).VisitUrlCookiesAsync("http://mobile.yangkeduo.com", true);
                List<CefSharp.Cookie> cookies = await context.GetCookieManager(null).VisitAllCookiesAsync();
                if (cookies == null || cookies.Count == 0)
                {
                    MessageBox.Show("请先登录账号");
                    return;
                }

                CefSharp.Cookie PDDAccessTokenCookie = cookies.Where(x => { return x.Name == "PDDAccessToken"; }).FirstOrDefault();
                CefSharp.Cookie pdd_user_id_cookie = cookies.Where(x => { return x.Name == "pdd_user_id"; }).FirstOrDefault();
                if (PDDAccessTokenCookie == null || pdd_user_id_cookie == null)
                {
                    MessageBox.Show("请先登录账号");
                    return;
                }
                //string address = IPProxy.GetNewIp().Replace("\n", "").Replace(" ", "").Replace("\t", "").Replace("\r", "");

                string url = "http://api.yangkeduo.com/api/oakstc/v14/goods/" + goodId + "?goods_id=" + goodId + "&pdduid=" + pdd_user_id_cookie.Value;

                var restclient = new RestClient(url);

                restclient.UserAgent = "android Mozilla/5.0 (Linux; Android 8.1.1; 1605-A01 Build/NMF26F; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/59.0.3071.82 Mobile Safari/537.36  phh_android_version/4.5.1 phh_android_build/228842 phh_android_channel/pp";

                //restclient.Proxy = RestClientUtil.CreateWebProxy(address);

                var request = new RestRequest(Method.GET);
                request.AddHeader("Content-Type", "application/json");
                request.AddHeader("Accept", "application/json, text/javascript, */*");
                request.AddHeader("Accept-Encoding", "gzip, deflate");
                request.AddHeader("AccessToken", PDDAccessTokenCookie.Value);
                request.AddHeader("Host", "api.yangkeduo.com");
                request.AddHeader("Referer", url);
                var response = restclient.Execute(request);

                if (string.IsNullOrWhiteSpace(response.Content))
                {
                    MessageBox.Show("获取数据为空！接口有问题啦");
                    return;
                }

                if (response.Content.Contains("verify_auth_token")
                   && response.Content.Contains("error_code"))
                {
                    MessageBox.Show("请输入验证码");
                    return;
                }

                if (response.Content.Contains("verify_auth_token")
                  && response.Content.Contains("error_code"))
                {
                    MessageBox.Show("请输入验证码");
                    return;
                }

                JObject jo = JObject.Parse(response.Content);
                dynamic skuObj = jo.GetValue("sku");
                PddGood pddGood = new PddGood();
                if (skuObj != null)
                {
                    dynamic groupObj = jo["group"];
                    pddGood.gID2 = groupObj[0]["group_id"] + "";
                    pddGood.gID1 = groupObj[1]["group_id"] + "";
                    pddGood.good_id = goodId;
                    string skuJson = JsonHelper.SerializeObject(skuObj);

                    pddGood.sku = skuJson;
                    pddGood.type = 2;
                }
                else
                {
                    MessageBox.Show("获取数据失败");
                    return;
                }
                dynamic promotion_activity_id = jo.GetValue("promotion_activity_id");
                if (promotion_activity_id != null)
                {
                    pddGood.atvid = promotion_activity_id + "";
                    //try
                    //{
                    //    var activity_id = activity["activity_id"];
                    //    pddGood.atvid = promotion_activity_id + "";
                    //}
                    //catch (Exception)
                    //{

                    //}

                    PddGood pdd = DataBaseHelper.SqLiteDBCon.Get<PddGood>(pddGood.good_id);
                    if (pdd == null)
                    {
                        long reslut = DataBaseHelper.SqLiteDBCon.Insert<PddGood>(pddGood);
                    }
                    else
                    {
                        DataBaseHelper.SqLiteDBCon.Update<PddGood>(pddGood);
                    }
                    MessageBox.Show("获取数据成功");

                }
                else
                {
                    MessageBox.Show("获取数据失败，可能是获取太频繁了");
                    return;
                }

            }
        }

        private async void button2_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(this.goodId))
            {
                return;
            }
            if (context == null)
            {
                return;
            }

            await context.GetCookieManager(null).FlushStoreAsync();

            List<CefSharp.Cookie> cookies2 = await context.GetCookieManager(null).VisitUrlCookiesAsync("http://mobile.yangkeduo.com", true);
            List<CefSharp.Cookie> cookies = await context.GetCookieManager(null).VisitAllCookiesAsync();
            if (cookies == null || cookies.Count == 0)
            {
                MessageBox.Show("请先登录账号");
                return;
            }

            CefSharp.Cookie PDDAccessTokenCookie = cookies.Where(x => { return x.Name == "PDDAccessToken"; }).FirstOrDefault();
            CefSharp.Cookie pdd_user_id_cookie = cookies.Where(x => { return x.Name == "pdd_user_id"; }).FirstOrDefault();
            if (PDDAccessTokenCookie == null || pdd_user_id_cookie == null)
            {
                MessageBox.Show("请先登录账号");
                return;
            }
            //string address = IPProxy.GetNewIp().Replace("\n", "").Replace(" ", "").Replace("\t", "").Replace("\r", "");
            string url = "http://mobile.yangkeduo.com/proxy/api/api/oak/integration/render?pdduid=" + pdd_user_id_cookie.Value;
            var restclient = new RestClient(url);
            //restclient.Proxy = RestClientUtil.CreateWebProxy(address);


            var request = new RestRequest(Method.POST);
            PddIntegration pddIntegration = new PddIntegration();

            pddIntegration.goods_id = long.Parse(goodId);
            pddIntegration.hostname = "mobile.yangkeduo.com";
            pddIntegration.page_from = 101;
            pddIntegration.page_version = 7;
            restclient.UserAgent = "android Mozilla/5.0 (Linux; Android 8.1.1; 1605-A01 Build/NMF26F; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/59.0.3071.82 Mobile Safari/537.36  phh_android_version/4.5.1 phh_android_build/228842 phh_android_channel/pp";

            request.AddHeader("AccessToken", PDDAccessTokenCookie.Value);
            //request.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/837.36 (KHTML, like Gecko) Chrome/82.0.3202.89 Safari/537.36");
            request.AddHeader("Host", "mobile.yangkeduo.com");
            request.AddHeader("Referer", url);

            request.AddObject(pddIntegration);
            var response = restclient.Execute(request);

            PaserGoogInfo(response);
        }

        private void PaserGoogInfo(IRestResponse response)
        {
            if (string.IsNullOrWhiteSpace(response.Content))
            {
                MessageBox.Show("获取数据为空！接口有问题啦");
                return;
            }

            if (response.Content.Contains("verify_auth_token")
               && response.Content.Contains("error_code"))
            {
                MessageBox.Show("请输入验证码");
                return;
            }

            if (response.Content.Contains("verify_auth_token")
              && response.Content.Contains("error_code"))
            {
                MessageBox.Show("请输入验证码");
                return;
            }

            JObject jo = JObject.Parse(response.Content);
            dynamic skuObj = jo.GetValue("sku");
            PddGood pddGood = new PddGood();
            if (skuObj != null)
            {
                dynamic groupObj = jo["goods"]["group"];
                pddGood.gID2 = groupObj[0]["group_id"] + "";
                pddGood.gID1 = groupObj[1]["group_id"] + "";
                pddGood.good_id = goodId;
                string skuJson = JsonHelper.SerializeObject(skuObj);

                pddGood.sku = skuJson;
                pddGood.type = 2;
            }
            else
            {
                MessageBox.Show("获取数据失败");
                return;
            }
            dynamic activity_collection = jo.GetValue("activity_collection");
            if (activity_collection != null)
            {
                try
                {
                    var activity_id = activity_collection["activity"]["activity_id"];
                    pddGood.atvid = activity_id + "";
                }
                catch (Exception)
                {

                }

                PddGood pdd = DataBaseHelper.SqLiteDBCon.Get<PddGood>(pddGood.good_id);
                if (pdd == null)
                {
                    long reslut = DataBaseHelper.SqLiteDBCon.Insert<PddGood>(pddGood);
                }
                else
                {
                    DataBaseHelper.SqLiteDBCon.Update<PddGood>(pddGood);
                }
                MessageBox.Show("获取数据成功");

            }
            else
            {
                MessageBox.Show("获取数据失败，可能是获取太频繁了");
                return;
            }
        }

        private void PddSkuFrom_Load(object sender, EventArgs e)
        {
            InitializeChromium();
        }

        private void button18_Click(object sender, EventArgs e)
        {

        }

        private void button3_Click(object sender, EventArgs e)
        {
            string url = "http://km.chuangnuotong.com/xinhq.php?id=" + this.goodId + "&user=455120494";
            string str = HttpHelper.HttpGet_anzhou(url, "gb2312");
            if (string.IsNullOrWhiteSpace(str))
            {
                MessageBox.Show("获取失败");
                return;
            }
            PddGood pddGood = new PddGood();

            pddGood.sku = str;
            pddGood.good_id = this.goodId;
            pddGood.type = 5;
            PddGood pdd = DataBaseHelper.SqLiteDBCon.Get<PddGood>(this.goodId);
            if (pdd == null)
            {
                long reslut = DataBaseHelper.SqLiteDBCon.Insert<PddGood>(pddGood);
            }
            else
            {
                DataBaseHelper.SqLiteDBCon.Update<PddGood>(pddGood);
            }

        }

        private async void button5_Click(object sender, EventArgs e)
        {
            List<CefSharp.Cookie> cookies = await context.GetCookieManager(null).VisitUrlCookiesAsync("http://mobile.yangkeduo.com", true);
            List<CefSharp.Cookie> cookies1 = await context.GetCookieManager(null).VisitAllCookiesAsync();
            if (cookies == null || cookies.Count == 0)
            {
                MessageBox.Show("请先登录账号");
                return;
            }
            await context.GetCookieManager(null).FlushStoreAsync();
        }

        private async void PddSkuFrom_FormClosing(object sender, FormClosingEventArgs e)
        {
            bool reslut = await context.GetCookieManager(null).FlushStoreAsync();
        }

        private void goods_id_TextChanged(object sender, EventArgs e)
        {
            this.goodId = this.goods_id.Text;
        }

        private void button2_Click_1(object sender, EventArgs e)
        {

        }

        private void button1_Click_1(object sender, EventArgs e)
        {

        }
    }
}

 